<template>
  <view>
    <view v-if="!successShow">
      <!-- 头部导航栏 -->
      <view class="top-navigate bg-yellow" style="padding: 53px 10px 15px 10px;">
        <view class="content cuIcon-back text-xl top-navigate-title" @click="goBack()"></view>
        <view class="text-xl top-navigate-title">身份认证</view>
      </view>
      <view class="cu-card case no-card">
        <view class="cu-item shadow">
          <view class="image">
            <image src="https://mp-8cee3ddd-8bba-44f8-bd49-93f17bd9d819.cdn.bspapp.com/identification-card/front.png"
              mode="widthFix"></image>
            <view class="cu-tag bg-blue">案例</view>
          </view>
        </view>
      </view>
      <view class="cu-card case no-card">
        <view class="cu-item shadow">
          <!-- 上传图片 -->
          <view class="image" @click="upIDCard" style="position: relative;">
            <view class="pic-add">
              <view class="cuIcon-add" style="font-size: 40px;">
              </view>
              <view class="">
                点击上传
              </view>
            </view>
            <image :src="base64str" :style="base64str!==''? 'z-index:1':''" class="add-img" mode="aspectFill"></image>
          </view>
        </view>
      </view>
      <view class="id-info border-top" v-if="name && idCard">
        <view class="id-info-title text-df ">姓名:
          <text class="text-gray" style="margin: 0 5px 0 20px;">{{name}}</text>
        </view>
        <view class="id-info-title text-df ">身份证号码:
          <text class="text-gray" style="margin: 0 5px 0 20px;">{{idCard}}</text>
        </view>
      </view>
    </view>
    
    <!-- 识别认证成功 -->
    <authentication-success :runnerInfo='runnerInfo' v-else></authentication-success>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        apiKey: 'uuDZtchDv8ypePIc3B7EvT8f',
        SecretKey: 'IN1qpRXmqRVCRn33Lsbz4YcFBTpMAysA',
        base64str: '',
        runnerInfo: {},
        successShow: false
      }
    },
    onLoad() {
      // 在百度智能云那边创建一个应用后可以获取到下面两个参数 api Key  和  Secret Key
      // this.apiKey = uni.getStorageSync('apiKey')
      // this.SecretKey = uni.getStorageSync('SecretKey')
    },
    methods: {
      goBack() {
        uni.navigateBack()
      },
      upIDCard() {
        let that = this
        uni.showActionSheet({
          itemList: ['从相册选择', '拍照'], // 显示的操作列表
          success: function(res) {
            if (!res.cancel) {
              if (res.tapIndex === 0) {
                // 用户选择了从相册选择
                uni.chooseImage({
                  count: 4, //默认9
                  sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                  sourceType: ['album'], //从相册选择
                  success: (res) => {
                    console.log(res);
                    that.ocrIDCard(res)
                  }
                });
              } else if (res.tapIndex === 1) {
                // 用户选择了拍照
                uni.chooseImage({
                  count: 1,
                  sourceType: ['camera'], // 拍照
                  success: function(res) {
                    // 用户拍照后的处理逻辑
                    console.log(res.tempFilePaths);
                    that.ocrIDCard(res)
                  }
                });
              }
            }
          }
        });
      },
      // access_token 有效期为 2592000 秒 / 30天
      getACSS_TOKEN() {
        let that = this
        uni.request({
          url: 'https://aip.baidubce.com/oauth/2.0/token',
          method: 'POST',
          data: {
            grant_type: 'client_credentials',
            client_id: this.apiKey, // 在百度智能云那边创建一个应用后可以获取
            client_secret: this.SecretKey // 在百度智能云那边创建一个应用后可以获取
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          success: res => {
            // console.log(res.data)
            uni.setStorageSync('access_token', res.data.access_token)
          }
        });
      },
      //识别
      ocrIDCard(res) {
        this.getACSS_TOKEN()
        let that = this
        let access_token = uni.getStorageSync('access_token')
        let tempFilePaths = res.tempFilePaths[0]
        // 图片转 base64
        uni.getFileSystemManager().readFile({
          filePath: tempFilePaths, //选择图片返回的相对路径  
          encoding: 'base64', //编码格式  
          success: v => { //成功的回调  
            let base64 = v.data // 返回的是没有 'data:image/jpeg;base64,'头的数据, 需要在页面显示图片可自行追加上  
            that.base64str = 'data:image/jpeg;base64,' + base64
            // 开始识别
            uni.request({
              url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' + access_token,
              method: 'POST',
              data: {
                image: base64,
                id_card_side: 'front' // 身份证 正反面  front：身份证含照片的一面  back：身份证带国徽的一面
              },
              header: {
                'Content-Type': 'application/x-www-form-urlencoded'
              },
              success: async res => {
                // console.log(res.data)
                if (res.data.words_result.姓名.words && res.data.words_result.公民身份号码.words) {
                  const name = res.data.words_result.姓名.words
                  const idCard = res.data.words_result.公民身份号码.words
                  const sex = res.data.words_result.性别.words
                  // uni.$showMsg('识别成功！')
                  const isAuth = await that.checkRegistration({
                    runnerName: name,
                    runnerIdCard: idCard
                  })
                  // 没有认证过
                  if (!isAuth) {
                    that.runnerInfo = {
                      runnerName: name,
                      runnerIdCard: idCard,
                      sex: sex,
                      avatarUrl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLjDSxkI8OsCLdsLudicUbiaUs7TiaPtUJkqbZ6MQshEyb3oUwa8afwgPM4toYHBX4a1KYoHicSgnaN2A/132',
                      orderCount:0,
                      deliveryMileage:0,
                      money:0
                    }
                    console.log(that.runnerInfo);
                    that.successShow=true
                  }else{
                    //已经认证过 返回登录界面登录
                    uni.$showMsg('您已经认证过，请登录!')
                    const timeOut= setTimeout(function() {  
                      uni.navigateBack()
                      clearTimeout(timeOut)
                    }, 2000);
                  }
                }
              }, //识别失败

            });
          }
        })
      },
      //查看是否已经注册
      async checkRegistration(info) {
        const db = uniCloud.database();
        const {
          result: res
        } = await db.collection('my_runner').where({
          runnerName: info.runnerName,
          runnerIdCard: info.runnerIdCard
        }).get()
        console.log(res);
        return res.data.length > 0 ? true : false
      },
    }
  }
</script>

<style lang="scss">
  .top-navigate {
    display: flex;
    justify-content: left;
    align-items: center;

    .top-navigate-title {
      margin: 0 5px;
      font-weight: bold;
    }

    .top-navigate-address {
      width: 150px;
      margin: 0 5px;
    }
  }

  .id-info {
    background-color: #ffffff;
    padding: 1rpx 30rpx;
    display: flex;
    min-height: 100rpx;
    justify-content: space-between;
    flex-direction: column;
    border-bottom: 1px solid #eee;

    .id-info-title {
      margin: 10px 0;
    }
  }

  .pic-add {
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #637cbb;
    z-index: 1;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .add-img {
    background-color: #EAF5FE;
    border: 1px solid black;
    height: 214px;
  }
</style>